#include <iostream>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/stat.h>

using std::cout;
using std::endl;

struct Student{
    Student(){}
    Student(int n, const char *na, float s):no(n), score(s)
    {
        strcpy(name, na);
    }
    int no;
    char name[20];
    float score;
};

void write()
{
    int fd = open("../data/student", O_CREAT | O_RDWR, 0666);
    if(fd < 0) {
        perror("open");
        return ;
    }
    Student stus[3] {{1, "张三", 89}, {2, "李四", 90}, {3, "王五", 80}};

    int ret = ::write(fd, &stus, sizeof(stus));
    if(ret < 0){
        perror("write");
        return;
    }

    close(fd);
}

void read()
{
    int fd = open("../data/student", O_RDWR);
    Student stu; 
    struct stat st;

    fstat(fd, &st);
    int total = st.st_size / sizeof(Student);
    int ret;
        // lseek(fd, sizeof(Student), SEEK_SET);
        // ret = ::read(fd, stu, sizeof(Student));
        // if(ret < 0){
        //     perror("read");
        //     return;
        // }
        // printf("no=%d, name=%s, score=%f\n", stu->no, stu->name, stu->score);
    for(int i{}; i < total; i++){
        lseek(fd, sizeof(Student) * i, SEEK_SET);
        ret = ::read(fd, &stu, sizeof(Student));
        if(ret < 0){
            perror("read");
            return;
        }
        printf("no=%d, name=%s, score=%f\n", stu.no, stu.name, stu.score);
    }

    close(fd);
}

int main(int args, char *argv[])
{
    // write();
    read();
    // cout << sizeof(Student) << endl;
    return 0;
}